package com.imdroid.carac.net;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.util.Log;

import com.imdroid.carac.IMDroid;

/**
 * Handles all the network communications to the wera server.
 */
public class HttpHelper {
	/**
	 * The TAG of the class
	 */
	private final static String TAG = "HttpHelper";
	/**
	 * the server address
	 */
	public static String webAddress = ServerAddress.webAddress;
	public static String ftpAddress = ServerAddress.ftpAddress;
	/**
	 * The timeout
	 */
	private static int timeoutConnection = 30 * 1000;
	private static int timeoutSocket = 50 * 1000;

	// public static String ServerAddress = "http://192.168.1.220:8080/webapp/";

	/**
	 * Request a given page with the given parameters, and get the response
	 * message. This method will suppress all exceptions, and when exception
	 * occurs, a string begins with "Error:" will be returned.
	 * 
	 * @param url
	 *            the page name
	 * @param params
	 *            the parameters
	 * @return the response string from server.
	 * @throws Exception
	 */
	public static String execute(String url, List<BasicNameValuePair> params)
			throws Exception {
		// Prepare the connection address
		HttpPost post = new HttpPost(webAddress + url);
		HttpEntity entity = null;
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters,
				timeoutConnection);
		HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

		Log.d(TAG, "Request :" + url);
		// Prepare the connection parameters
		if (params != null)
			entity = new UrlEncodedFormEntity(params, "UTF-8");
		HttpClient client = new DefaultHttpClient(httpParameters);
		post.setEntity(entity);
		// Send the request.
		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String text = EntityUtils.toString(response.getEntity());
			Log.d(TAG, "response :" + text);
			return text;
		} else
			throw new Exception("Error:"
					+ EntityUtils.toString(response.getEntity()));
	}

	/**
	 * Download file from the server
	 * 
	 * @param targetFile
	 *            the file name
	 * @throws Exception
	 */
	public static void download(String targetFile) throws Exception {
		String target = IMDroid.TEMP_FOLDER + targetFile;
		HttpURLConnection huc = null;
		FileOutputStream fos = null;
		InputStream is = null;
		try {
			System.out.println("开始下载：　" + new Date());
			huc = (HttpURLConnection) (new URL(webAddress
					+ "DownloadFile?fileName=" + targetFile).openConnection());
			System.out.println("------" + target + "------");
			fos = new FileOutputStream(target);
			is = huc.getInputStream();
			System.out.println("连接成功：  " + new Date());
			int len = 0;
			byte[] buffer = new byte[4096];
			while ((len = is.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
				fos.flush();
			}
			System.out.println("下载完毕：　" + new Date());
		} catch (Exception e) {
			System.out.println("下载出错：　" + new Date());
			e.printStackTrace();
			throw e;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (fos != null) {
				try {
					fos.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (huc != null) {
				try {
					huc.disconnect();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 获取短地址
	 * 
	 * @param url
	 *            the long url
	 * @return the url after shorten
	 * @throws Exception
	 * @throws ParseException
	 */
	public static String getShortenURL(String url) throws ParseException,
			Exception {
		String requestURL = "http://126.am/api!shorten.action";
		List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("key",
				"e14ac396f1ec4a3aa7d382b78d8c458e"));
		params.add(new BasicNameValuePair("longUrl", url));

		// Prepare the connection address
		HttpPost post = new HttpPost(requestURL);
		HttpEntity entity = null;

		Log.d(TAG, "Request :" + url);

		// Prepare the connection parameters
		entity = new UrlEncodedFormEntity(params, "UTF-8");
		HttpClient client = new DefaultHttpClient();
		post.setEntity(entity);

		// Send the request.
		HttpResponse response = client.execute(post);

		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			String jsonText = EntityUtils.toString(response.getEntity());
			Log.d(TAG, "response :" + jsonText);
			JSONTokener jsonParser = new JSONTokener(jsonText);
			JSONObject baiduReturn = (JSONObject) jsonParser.nextValue();
			int status = baiduReturn.getInt("status_code");
			if (status == 200) {
				return baiduReturn.getString("url");
			} else {
				throw new Exception("Error - " + status);
			}

		} else {
			throw new Exception("Error:"
					+ EntityUtils.toString(response.getEntity()));
		}

	}
}
